import { useCallback } from 'react';
import { useDispatch , useSelector, TypedUseSelectorHook } from 'react-redux';
import {
    fetchAllConservations,
    fetchConservationList,
    fetchConservationDetail,
    createConservation,
    updateConservation,
    deleteConservation, generateAnswer,
} from '@/services/conservationService';
import { RootState, AppDispatch } from '@/stores';
import { resetConservationInfo, setConservationInfo } from '@/stores/conservationSlice';
import {
    ConservationCreateReq,
    ConservationDetail,
    ConservationUpdateReq,
    GetAllConservationParam,
    GetConservationListParam
} from "@/types/conservationType";


export function useDispatchConservation() {
    const dispatch = useDispatch<AppDispatch>();

    // Get all Conservations
    const getAllConservations = useCallback((param: GetAllConservationParam) => {
        return dispatch(fetchAllConservations(param));
    }, [dispatch]);

    // Get Conservation list (pagination)
    const getConservationList = useCallback((params?: GetConservationListParam) => {
        return dispatch(fetchConservationList(params));
    }, [dispatch]);

    // Get Conservation details
    const getConservationDetail = useCallback((conservationUuid: string) => {
        return dispatch(fetchConservationDetail(conservationUuid));
    }, [dispatch]);

    // Create a new Conservation
    const addConservation = useCallback((conservationData: ConservationCreateReq) => {
        return dispatch(createConservation(conservationData));
    }, [dispatch]);

    // Update Conservation information
    const updateConservationInfo = useCallback((conservationUuid: string, data: ConservationUpdateReq) => {
        return dispatch(updateConservation({ conservationUuid, data }));
    }, [dispatch]);

    // Delete Conservations
    const removeConservation = useCallback((pk: string) => {
        return dispatch(deleteConservation(pk));
    }, [dispatch]);

    const generateAgentAnswer = useCallback((uuid: string, data: {}) => {
        return dispatch(generateAnswer({uuid, data}));
    }, [dispatch]);

    // Set partial Conservation info (partial update)
    const setConservationPartialInfo = useCallback((conservationInfo: Partial<ConservationDetail>) => {
        dispatch(setConservationInfo(conservationInfo));
    }, [dispatch]);

    // Reset Conservation info
    const resetConservation = useCallback(() => {
        dispatch(resetConservationInfo());
    }, [dispatch]);

    return {
        getAllConservations,
        getConservationList,
        getConservationDetail,
        addConservation,
        updateConservationInfo,
        removeConservation,
        generateAgentAnswer,
        setConservationPartialInfo,
        resetConservation,
    };
}

// Create a typed useSelector hook
export const useConservationSelector: TypedUseSelectorHook<RootState> = useSelector;
